import { _decorator, Component, Node, ParticleSystem, Sprite, SpriteFrame, tween, v3 } from 'cc';
import { CowGame } from '../CowGame';
const { ccclass, property } = _decorator;

@ccclass('Rope')
export class Rope extends Component {

    @property(SpriteFrame)
    emptyRope: SpriteFrame

    @property([SpriteFrame])
    cowRopes: SpriteFrame[] = []

    private isShoot: boolean

    // private effectParticle: ParticleSystem

    private cowGame: CowGame

    private ropeSprite: Sprite

    onLoad(): void {
        this.node.setPosition(v3(0, -560, 0))
        this.isShoot = false;
        // this.effectParticle = this.node.getChildByName("Effect").getComponent(ParticleSystem)

        this.ropeSprite = this.node.getComponent(Sprite)
    }

    init(cowGame: CowGame) {
        this.cowGame = cowGame
        this.setRopeEmpty()
    }

    // 空绳子
    setRopeEmpty() {
        this.ropeSprite.spriteFrame = this.emptyRope;
    }

    // 有牛的绳子
    setRopeCow(cowType: number) {
        if (cowType < 0 || cowType >= 3) {
            return;
        }
        this.ropeSprite.spriteFrame = this.cowRopes[cowType]
    }

    // 发射
    shoot() {
        if (this.isShoot) {
            return;
        }
        this.isShoot = true;

        tween(this.node)
            .to(0.5, { position: v3(0, 70) })
            .call(() => {
                let cowIdx = this.cowGame.hitCow()
                if (cowIdx >= 0 && cowIdx < 3) {
                    let position = this.node.getPosition()
                    this.node.setPosition(position.x, 112, 0)
                    // this.effectParticle.clear()
                    this.setRopeCow(cowIdx)
                }
            }).to(0.5, { position: v3(0, -560, 0) })
            .call(() => {
                this.setRopeEmpty()
                this.isShoot = false;
            }).start()
    }

}

